package main

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/wtf/mahjong/model"
)

type Map map[string]interface{}

type Friend struct {
	OpenId    string `json:"uniqueid"`
	ShareCode string `json:"share_code"`
}

func inviteAction(userInfo model.User, friendInfo model.User) (err error) {
	// 获取当日时间戳
	var today = getNow()
	var inviteInfo, inviteTodayInfo model.Invite
	// 判断是否有记录
	inviteInfo, err = model.InviteGetById(userInfo.UniqueId)
	if err != nil { // 没有记录,添加
		inviteInfo = model.Invite{OpenId: userInfo.UniqueId, Time: today}
		err = model.InviteCreate(&inviteInfo)
		if err != nil {
			// invitePower:添加邀请记录失败
			return
		}
	}
	inviteTodayInfo, err = model.InviteGetByIdTime(inviteInfo.OpenId, today)
	if err == nil { // 有今天记录,更新
		inviteList := inviteTodayInfo.Invite
		// 好友列表
		var inviteArr []string
		// 将好友列表转为切片
		if inviteList != "" {
			inviteArr = strings.Split(inviteList, ",")
			// 判断是否超过5
			if len(inviteArr) >= 5 {
				err = errors.New("今日邀请已达上限")
				return
			}

			// 判断今日是否已经邀请
			for _, v := range inviteArr {
				if v == friendInfo.UniqueId {
					err = errors.New("今日已经邀请")
					return
				}
			}
			inviteTodayInfo.IsGet = inviteTodayInfo.IsGet + ",0"
		} else {
			inviteTodayInfo.IsGet = "0"
		}

		inviteArr = append(inviteArr, friendInfo.UniqueId)
		inviteTodayInfo.Invite = strings.Replace(strings.Trim(fmt.Sprint(inviteArr), "[]"), " ", ",", -1)
		inviteTodayInfo.IsGetLast = 0

		err = model.InviteUpdateInvite(inviteTodayInfo)
		if err != nil { // invitePower:更新今日邀请数据失败
			return
		}
	} else { // 没有今天记录,更新全新数据+今日时间戳
		inviteInfo.Invite = friendInfo.UniqueId
		inviteInfo.IsGet = "0"
		inviteInfo.IsGetLast = 0
		inviteInfo.Time = today

		err = model.InviteUpdateInvite(inviteInfo)
		if err != nil { // invitePower:全新更新邀请数据失败
			return
		}
	}
	return
}

func checkMonth(openId string) (flag int, err error) {
	var userInfo model.User
	flag = 0
	userInfo, err = model.UserByUniqueId(openId)
	if err != nil {
		return
	}

	if userInfo.MonthStart == 0 {
		return
	}

	now := int(time.Now().Unix())

	if (userInfo.MonthStart - now) <= 20*60 { // 月卡到期时间小于20分钟 失效
		// 设置月卡失效
		err = userInfo.Update("month_start", "0")
		return
	} else {
		flag = 1
	}
	return
}

func checkEight(openId string) (flag int, err error) {
	var userInfo model.User
	flag = 0
	userInfo, err = model.UserByUniqueId(openId)
	if err != nil {
		return
	}

	if userInfo.Eight == 0 {
		return
	}

	now := int(time.Now().Unix())

	if (userInfo.Eight - now) <= 20*60 { // eight到期时间小于20分钟 失效
		// 设置月卡失效
		err = userInfo.Update("eight", "0")
		return
	} else {
		flag = 1
	}
	return
}
